package com.celesea.configuration.redis;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.ObjectProvider;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.boot.autoconfigure.condition.ConditionalOnMissingBean;
import org.springframework.boot.autoconfigure.data.redis.RedisAutoConfiguration;
import org.springframework.boot.autoconfigure.data.redis.RedisProperties;
import org.springframework.boot.context.properties.ConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;
import org.springframework.data.redis.connection.RedisClusterConfiguration;
import org.springframework.data.redis.connection.RedisConnectionFactory;
import org.springframework.data.redis.connection.RedisSentinelConfiguration;
import org.springframework.data.redis.connection.jedis.JedisConnectionFactory;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.serializer.StringRedisSerializer;

import java.net.UnknownHostException;

@Configuration
public class RedisConfiguration extends RedisAutoConfiguration {
    private Logger logger = LoggerFactory.getLogger(getClass());

    @Bean({"redisProperties", "properties"})
    @ConfigurationProperties(prefix = "spring.redis")
    public RedisProperties redisProperties() {
        return new RedisProperties();
    }

    @Bean({"ssoRedisProperties"})
    @ConfigurationProperties(prefix = "celesea.sso.redis")
    public RedisProperties ssoRedisProperties() {
        return new RedisProperties();
    }

    public static class SsoRedisConnectionConfiguration extends  RedisConnectionConfiguration{

        public SsoRedisConnectionConfiguration(
                @Qualifier("ssoRedisProperties")
                RedisProperties ssoRedisProperties,
                ObjectProvider<RedisSentinelConfiguration> sentinelConfiguration,
                ObjectProvider<RedisClusterConfiguration> clusterConfiguration) {
            super(ssoRedisProperties, sentinelConfiguration, clusterConfiguration);
        }

        @Bean("ssoConnectionFactory")
        @ConditionalOnMissingBean({RedisConnectionFactory.class})
        public JedisConnectionFactory ssoRedisConnectionFactory() throws UnknownHostException {
            return super.redisConnectionFactory();
        }
    }

    @Bean("ssoRedisTemplate")
    public RedisTemplate redisTemplate(@Qualifier("ssoConnectionFactory") RedisConnectionFactory connectionFactory) {
        RedisTemplate template = new RedisTemplate();
        template.setConnectionFactory(connectionFactory);
        template.setKeySerializer(new StringRedisSerializer());
        template.setHashKeySerializer(new StringRedisSerializer());
        return template;
    }
}
